<template>
  <div class="control-chart-analysis" v-loading="loading">
    <el-row :gutter="20">
      <!-- 控制图类型选择 -->
      <el-col :span="24">
        <el-card shadow="hover" class="chart-type-card">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="16" :md="16">
              <el-radio-group v-model="selectedChartType" @change="handleChartTypeChange">
                <el-radio-button label="xr">X-R控制图</el-radio-button>
                <el-radio-button label="xs">X-S控制图</el-radio-button>
                <el-radio-button label="p">P控制图</el-radio-button>
                <el-radio-button label="np">NP控制图</el-radio-button>
                <el-radio-button label="u">U控制图</el-radio-button>
                <el-radio-button label="c">C控制图</el-radio-button>
              </el-radio-group>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <el-button type="primary" @click="exportChart" style="float: right;" :disabled="!hasData">
                <i class="el-icon-download"></i> 导出报告
              </el-button>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 控制图参数概览 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card shadow="hover" class="param-card">
          <div slot="header" class="card-header">
            <span>控制图参数</span>
          </div>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :md="8">
              <div class="param-item">
                <div class="item-title">过程均值</div>
                <div class="item-value">{{ controlChartData.chartParams?.avg || 'N/A' }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <div class="param-item">
                <div class="item-title">样本数量</div>
                <div class="item-value">{{ controlChartData.chartParams?.sampleSize || 'N/A' }}</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="8" :md="8">
              <div class="param-item">
                <div class="item-title">过程状态</div>
                <div class="item-value" :class="getProcessStateClass">{{ getProcessState }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- X控制图 -->
    <el-row :gutter="20" class="chart-row" v-if="isXrOrXsChart">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span>X控制图 (个别值控制图)</span>
          </div>
          <div class="chart-container" ref="xChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- R/S控制图 -->
    <el-row :gutter="20" class="chart-row" v-if="isXrOrXsChart">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span>{{ selectedChartType === 'xr' ? 'R控制图 (极差控制图)' : 'S控制图 (标准差控制图)' }}</span>
          </div>
          <div class="chart-container" ref="rsChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 属性控制图 (p, np, u, c) -->
    <el-row :gutter="20" class="chart-row" v-if="isAttributeChart">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="card-header">
            <span>{{ getAttributeChartTitle }}</span>
          </div>
          <div class="chart-container" ref="attributeChart"></div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 控制图规则解释 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>控制图解读</span>
          </div>
          <div class="interpretation-content">
            <el-alert
              :title="getControlChartAlert.title"
              :type="getControlChartAlert.type"
              :description="getControlChartAlert.description"
              show-icon
              :closable="false">
            </el-alert>
            
            <div class="rules-section" v-if="hasData">
              <h4>控制图规则：</h4>
              <el-divider></el-divider>
              <el-table :data="controlRules" style="width: 100%">
                <el-table-column prop="rule" label="规则" width="180"></el-table-column>
                <el-table-column prop="description" label="描述"></el-table-column>
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="scope">
                    <el-tag :type="scope.row.violated ? 'danger' : 'success'">
                      {{ scope.row.violated ? '违反' : '正常' }}
                    </el-tag>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'

export default {
  name: "ControlChartAnalysis",
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    queryParams: {
      type: Object,
      required: true
    },
    controlChartData: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      selectedChartType: 'xr',
      xChart: null,
      rsChart: null,
      attributeChart: null,
      controlRules: [
        { rule: "规则1", description: "有点超出控制限", violated: false },
        { rule: "规则2", description: "连续7点在中心线的一侧", violated: false },
        { rule: "规则3", description: "连续7点递增或递减", violated: false },
        { rule: "规则4", description: "连续14点交替上下波动", violated: false },
        { rule: "规则5", description: "3点中有2点在距离中心线2σ外的同一侧", violated: false },
        { rule: "规则6", description: "连续5点有4点在距离中心线1σ外的同一侧", violated: false },
        { rule: "规则7", description: "连续15点在中心线上下1σ区域内", violated: false },
        { rule: "规则8", description: "连续8点在距离中心线1σ外", violated: false }
      ]
    }
  },
  computed: {
    hasData() {
      return this.controlChartData.measurements && this.controlChartData.measurements.length > 0;
    },
    isXrOrXsChart() {
      return this.selectedChartType === 'xr' || this.selectedChartType === 'xs';
    },
    isAttributeChart() {
      return ['p', 'np', 'u', 'c'].includes(this.selectedChartType);
    },
    getProcessState() {
      if (!this.hasData) return 'N/A';
      
      const violations = this.controlRules.filter(rule => rule.violated);
      if (violations.length === 0) return '受控';
      if (violations.length <= 2) return '警告';
      return '失控';
    },
    getProcessStateClass() {
      if (!this.hasData) return '';
      
      const violations = this.controlRules.filter(rule => rule.violated);
      if (violations.length === 0) return 'text-excellent';
      if (violations.length <= 2) return 'text-warning';
      return 'text-poor';
    },
    getAttributeChartTitle() {
      const chartTypes = {
        'p': 'P控制图 (不合格品率控制图)',
        'np': 'NP控制图 (不合格品数控制图)',
        'u': 'U控制图 (单位不合格数控制图)',
        'c': 'C控制图 (不合格数控制图)'
      };
      return chartTypes[this.selectedChartType] || '属性控制图';
    },
    getControlChartAlert() {
      if (!this.hasData) {
        return {
          title: '没有数据',
          type: 'info',
          description: '请选择产品、批次和参数，并查询数据。'
        };
      }
      
      const violations = this.controlRules.filter(rule => rule.violated);
      if (violations.length === 0) {
        return {
          title: '过程处于统计控制状态',
          type: 'success',
          description: '所有测量点都在控制限内，且未违反任何控制规则。过程稳定，仅存在随机变异。'
        };
      } else if (violations.length <= 2) {
        return {
          title: '过程有警告信号',
          type: 'warning',
          description: `检测到${violations.length}项控制规则违反。这些可能是失控的早期信号，建议关注并采取预防措施。`
        };
      } else {
        return {
          title: '过程失控',
          type: 'error',
          description: `检测到${violations.length}项控制规则违反。过程存在特殊原因变异，需要立即调查并采取纠正措施。`
        };
      }
    }
  },
  watch: {
    'controlChartData': {
      handler() {
        this.$nextTick(() => {
          this.updateControlRulesStatus();
          this.initCharts();
        });
      },
      deep: true
    },
    'loading': {
      handler(newVal) {
        if (!newVal) {
          this.$nextTick(() => {
            this.updateControlRulesStatus();
            this.initCharts();
          });
        }
      }
    }
  },
  mounted() {
    this.updateControlRulesStatus();
    this.initCharts();
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    this.disposeCharts();
  },
  methods: {
    handleChartTypeChange(newType) {
      this.$emit('chart-type-changed', newType);
    },
    updateControlRulesStatus() {
      // 根据控制图数据更新规则违反状态
      // 这里假设controlChartData中包含了规则违反的信息
      if (this.hasData && this.controlChartData.ruleViolations) {
        this.controlRules.forEach((rule, index) => {
          rule.violated = this.controlChartData.ruleViolations.includes(index + 1);
        });
      } else {
        this.controlRules.forEach(rule => {
          rule.violated = false;
        });
      }
    },
    resizeCharts() {
      try {
        if (this.xChart && this.$refs.xChart && this.xChart.resize) {
          this.xChart.resize();
        }
        
        if (this.rsChart && this.$refs.rsChart && this.rsChart.resize) {
          this.rsChart.resize();
        }
        
        if (this.attributeChart && this.$refs.attributeChart && this.attributeChart.resize) {
          this.attributeChart.resize();
        }
      } catch (error) {
        console.error('Error resizing control charts:', error);
      }
    },
    disposeCharts() {
      try {
        if (this.xChart) {
          this.xChart.dispose();
          this.xChart = null;
        }
        
        if (this.rsChart) {
          this.rsChart.dispose();
          this.rsChart = null;
        }
        
        if (this.attributeChart) {
          this.attributeChart.dispose();
          this.attributeChart = null;
        }
      } catch (error) {
        console.error('Error disposing control charts:', error);
      }
    },
    initCharts() {
      this.initXChart();
      this.initRSChart();
      this.initAttributeChart();
    },
    initXChart() {
      if (!this.isXrOrXsChart || !this.$refs.xChart) return;
      
      if (this.xChart) {
        this.xChart.dispose();
      }
      
      this.xChart = echarts.init(this.$refs.xChart);
      
      if (!this.hasData) {
        this.xChart.setOption({
          title: {
            text: '没有控制图数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      // 确保数据存在并添加必要的默认值
      const measurements = this.controlChartData.measurements || [];
      if (measurements.length === 0) {
        this.xChart.setOption({
          title: {
            text: '没有足够的测量数据点生成控制图',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      const xAxisData = measurements.map((_, index) => index + 1);
      const seriesData = measurements.map(item => item.xValue || item.value);
      const xLimits = this.controlChartData.xChartLimits || {
        ucl: 0,
        cl: 0,
        lcl: 0
      };
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          name: '样本序号',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: {
          type: 'value',
          name: '测量值',
          nameRotate: 90,
          nameLocation: 'middle',
          nameGap: 50
        },
        series: [
          {
            name: '测量值',
            type: 'line',
            data: seriesData,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 2
            },
            markLine: {
              silent: true,
              data: [
                { 
                  name: 'UCL', 
                  yAxis: xLimits.ucl !== undefined && xLimits.ucl !== null && !isNaN(xLimits.ucl) ? parseFloat(xLimits.ucl) : null, 
                  lineStyle: { color: '#f56c6c' },
                  label: { formatter: 'UCL: {c}' }
                },
                { 
                  name: 'CL', 
                  yAxis: xLimits.cl !== undefined && xLimits.cl !== null && !isNaN(xLimits.cl) ? parseFloat(xLimits.cl) : null, 
                  lineStyle: { color: '#67c23a' },
                  label: { formatter: 'CL: {c}' }
                },
                { 
                  name: 'LCL', 
                  yAxis: xLimits.lcl !== undefined && xLimits.lcl !== null && !isNaN(xLimits.lcl) ? parseFloat(xLimits.lcl) : null, 
                  lineStyle: { color: '#f56c6c' },
                  label: { formatter: 'LCL: {c}' }
                }
              ].filter(item => item.yAxis !== null)
            }
          }
        ]
      };
      
      this.xChart.setOption(option);
    },
    initRSChart() {
      if (!this.isXrOrXsChart || !this.$refs.rsChart) return;
      
      if (this.rsChart) {
        this.rsChart.dispose();
      }
      
      this.rsChart = echarts.init(this.$refs.rsChart);
      
      if (!this.hasData) {
        this.rsChart.setOption({
          title: {
            text: '没有控制图数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      // 确保数据存在并添加必要的默认值
      const measurements = this.controlChartData.measurements || [];
      if (measurements.length === 0) {
        this.rsChart.setOption({
          title: {
            text: '没有足够的测量数据点生成控制图',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      const xAxisData = measurements.map((_, index) => index + 1);
      const isRChart = this.selectedChartType === 'xr';
      const seriesData = measurements.map(item => isRChart ? 
        (item.rValue || Math.abs((item.value || 0) - (this.controlChartData.chartParams?.avg || 0))) : 
        (item.sValue || 0));
      const limits = isRChart ? 
        (this.controlChartData.rChartLimits || { ucl: 0, cl: 0, lcl: 0 }) : 
        (this.controlChartData.sChartLimits || { ucl: 0, cl: 0, lcl: 0 });
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          name: '样本序号',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: {
          type: 'value',
          name: isRChart ? '极差值' : '标准差',
          nameRotate: 90,
          nameLocation: 'middle',
          nameGap: 50
        },
        series: [
          {
            name: isRChart ? '极差值' : '标准差',
            type: 'line',
            data: seriesData,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 2
            },
            markLine: {
              silent: true,
              data: [
                { 
                  name: 'UCL', 
                  yAxis: limits?.ucl !== undefined && limits?.ucl !== null && !isNaN(limits?.ucl) ? parseFloat(limits?.ucl) : null, 
                  lineStyle: { color: '#f56c6c' },
                  label: { formatter: 'UCL: {c}' }
                },
                { 
                  name: 'CL', 
                  yAxis: limits?.cl !== undefined && limits?.cl !== null && !isNaN(limits?.cl) ? parseFloat(limits?.cl) : null, 
                  lineStyle: { color: '#67c23a' },
                  label: { formatter: 'CL: {c}' }
                },
                { 
                  name: 'LCL', 
                  yAxis: limits?.lcl !== undefined && limits?.lcl !== null && !isNaN(limits?.lcl) ? parseFloat(limits?.lcl) : null, 
                  lineStyle: { color: '#f56c6c' },
                  label: { formatter: 'LCL: {c}' }
                }
              ].filter(item => item.yAxis !== null)
            }
          }
        ]
      };
      
      this.rsChart.setOption(option);
    },
    initAttributeChart() {
      if (!this.isAttributeChart || !this.$refs.attributeChart) return;
      
      if (this.attributeChart) {
        this.attributeChart.dispose();
      }
      
      this.attributeChart = echarts.init(this.$refs.attributeChart);
      
      if (!this.hasData) {
        this.attributeChart.setOption({
          title: {
            text: '没有控制图数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      // 确保数据存在并添加必要的默认值
      const measurements = this.controlChartData.measurements || [];
      if (measurements.length === 0) {
        this.attributeChart.setOption({
          title: {
            text: '没有足够的测量数据点生成控制图',
            left: 'center',
            top: 'middle',
            textStyle: {
              fontSize: 16,
              color: '#999'
            }
          }
        });
        return;
      }
      
      const xAxisData = measurements.map((_, index) => index + 1);
      const limitKey = this.selectedChartType + 'ChartLimits';
      const limits = this.controlChartData[limitKey] || {
        ucl: 0,
        cl: 0,
        lcl: 0
      };
      
      let seriesData = [], yAxisName = '';
      
      // 为不同的控制图类型分配默认值
      switch (this.selectedChartType) {
        case 'p':
          seriesData = measurements.map(item => item.pValue || (item.isInControl == 0 ? 1 : 0));
          yAxisName = '不合格品率';
          break;
        case 'np':
          seriesData = measurements.map(item => item.npValue || (item.isInControl == 0 ? 1 : 0));
          yAxisName = '不合格品数';
          break;
        case 'u':
          seriesData = measurements.map(item => item.uValue || (item.isInControl == 0 ? 1 : 0));
          yAxisName = '单位不合格数';
          break;
        case 'c':
          seriesData = measurements.map(item => item.cValue || (item.isInControl == 0 ? 1 : 0));
          yAxisName = '不合格数';
          break;
        default:
          seriesData = measurements.map(item => item.isInControl == 0 ? 1 : 0);
          yAxisName = '不合格率';
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        grid: {
          left: '5%',
          right: '5%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          name: '样本序号',
          nameLocation: 'middle',
          nameGap: 30
        },
        yAxis: {
          type: 'value',
          name: yAxisName,
          nameRotate: 90,
          nameLocation: 'middle',
          nameGap: 50
        },
        series: [
          {
            name: yAxisName,
            type: 'line',
            data: seriesData,
            symbol: 'circle',
            symbolSize: 8,
            lineStyle: {
              width: 2
            },
            markLine: {
              silent: true,
              data: [
                { 
                  name: 'UCL', 
                  yAxis: limits?.ucl !== undefined && limits?.ucl !== null && !isNaN(limits?.ucl) ? parseFloat(limits?.ucl) : null, 
                  lineStyle: { color: '#f56c6c' },
                  label: { formatter: 'UCL: {c}' }
                },
                { 
                  name: 'CL', 
                  yAxis: limits?.cl !== undefined && limits?.cl !== null && !isNaN(limits?.cl) ? parseFloat(limits?.cl) : null, 
                  lineStyle: { color: '#67c23a' },
                  label: { formatter: 'CL: {c}' }
                },
                { 
                  name: 'LCL', 
                  yAxis: limits?.lcl !== undefined && limits?.lcl !== null && !isNaN(limits?.lcl) ? parseFloat(limits?.lcl) : null, 
                  lineStyle: { color: '#f56c6c' },
                  label: { formatter: 'LCL: {c}' }
                }
              ].filter(item => item.yAxis !== null)
            }
          }
        ]
      };
      
      this.attributeChart.setOption(option);
    },
    exportChart() {
      // 导出图表为图片或PDF
      this.$message({
        message: '报告导出功能开发中...',
        type: 'info'
      });
    }
  }
}
</script>

<style scoped>
.control-chart-analysis {
  padding: 10px 0;
}
.chart-type-card {
  margin-bottom: 20px;
}
.chart-row {
  margin-bottom: 20px;
}
.chart-card, .param-card {
  height: 100%;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.chart-container {
  height: 300px;
  width: 100%;
}
.param-item {
  text-align: center;
  padding: 10px 0;
}
.item-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.item-value {
  font-size: 24px;
  font-weight: bold;
}
.text-excellent {
  color: #67c23a;
}
.text-warning {
  color: #e6a23c;
}
.text-poor {
  color: #f56c6c;
}
.interpretation-content {
  padding: 10px;
}
.rules-section {
  margin-top: 20px;
}
</style> 